﻿using Demo.Controllers;
using System;
using System.Numerics;

namespace MRMDS.Module
{
    public static class Root
    {
        public static HashSet<string> Tokens { get; set; }
        private static string password;


        static Root()
        {
            password = "admin";
            Tokens = new HashSet<string>();
        }

        public static string? GenerateToken(string pw)
        {
            if (pw != password)
            {
                return null;
            }
            string token;
            do
            {
                token = Guid.NewGuid().ToString();
            } while (Tokens.Contains(token));
            return token;
        }

        public static bool IsTokenValide(string token)
        {
            return Tokens.Contains(token);
        }

        public static bool ProgramReset()
        {
            return Reset(password);
        }

        public static bool Reset(string pw)
        {
            if (pw == password)
            {
                GlobalManager.Instance.Reset();
                Tokens.Clear();
                LoadTokensFromFile();
                return true;
            }
            return false;
        }

        private static void LoadTokensFromFile()
        {
            string path = Directory.GetCurrentDirectory() + "\\Tokens.txt";
            if(!File.Exists(path))
            {
                Console.WriteLine("Can not find tokens");
                return;
            }
            Console.WriteLine("Load tokens from  " + path);
            using (StreamReader reader = File.OpenText(path))
            {
                while (true)
                {
                    var token = reader.ReadLine();
                    if (token == null)
                    {
                        break;
                    }
                    token.Trim();
                    if (token.Length == 0)
                    {
                        continue;
                    }
                    Root.Tokens.Add(token);
                }
            }
        }
    }
}